import { login, projectlLoginInfo, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter, constantRoutes } from '@/router'

const state = {
  token: getToken(),
  name: sessionStorage.getItem('store') ? JSON.parse(sessionStorage.getItem('store')).user.name : '',
  avatar: '',
  introduction: '',
  isLogin: false,
  // roles:
  projects: [],
  roles: sessionStorage.getItem('store') ? JSON.parse(sessionStorage.getItem('store')).user.roles : [],
  userInfo:  sessionStorage.getItem('store') ? JSON.parse(sessionStorage.getItem('store')).user.userInfo : null,
  accountType: sessionStorage.getItem('store') ? JSON.parse(sessionStorage.getItem('store')).user.accountType :  '',
  id: sessionStorage.getItem('store') ? JSON.parse(sessionStorage.getItem('store')).user.id :  '',
  account:  sessionStorage.getItem('store') ? JSON.parse(sessionStorage.getItem('store')).user.account : ''
}

const mutations = {
  set_Login: (state, isLogin) => {
    state.isLogin = isLogin
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_ACCOUNTTYPE: (state, accountType) => {
    state.accountType = accountType
  },
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_ACCOUNT: (state, account) => {
    state.account = account
  },
  SET_PROJECTS: (state, projects) => {
    state.projects = projects
  }
}

const actions = {
  // user login
  login({ commit }, userInfo, dispatch) {
    const { username, password, loginBrowType, loginIp } = userInfo
    return new Promise((resolve, reject) => {
      login({ account: username.trim(), password: password, loginBrowType: loginBrowType.toString(), loginIp: loginIp.toString(),  }).then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }
        let roles = []
        if(data.accountType !== 0){
          roles = ['custom']
        } else if(data.accountType == 0) {
          roles = ['admin']
        }
        commit('SET_ROLES', roles)
        commit('SET_USERINFO', data)
        commit('SET_ID', data.id)
        commit('SET_NAME', data.userName)
        commit('SET_ACCOUNT', data.account)
        commit('SET_ACCOUNTTYPE', data.accountType)
        commit('set_Login', true)
        commit('SET_PROJECTS', [])


        this.dispatch('permission/generateRoutes', roles , { root: true }).then(res => {
          //   console.log(res, 'res')
          let accessRoutes = res
          // dynamically add accessible routes
          resetRouter()
          // router.matcher = new VueRouter({ mode: 'history', routes: constantRoutes }).matcher;

          // router.options.routes.push(...accessRoutes)
            router.addRoutes(accessRoutes)
          //   console.log(router)
          //   resolve(accessRoutes)
          resolve(data)
        })
      }).catch(error => {
        reject(error)
      })
    })
  },

  // project login
  projectLogin({ commit }, userInfo, dispatch) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      projectlLoginInfo({ subAccount: username.trim(), subAccPwd: password }).then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }
        let roles = ['project']

        commit('SET_ROLES', roles)
        commit('SET_USERINFO', data)
        commit('SET_ID', data.id)
        commit('SET_NAME', data.userName)
        commit('SET_ACCOUNT', data.account)
        commit('SET_ACCOUNTTYPE', data.accountType)
        commit('set_Login', true)
        commit('SET_PROJECTS', [])



        this.dispatch('permission/generateRoutes', roles , { root: true }).then(res => {
          //console.log(res, 'res')
          let accessRoutes = res
          // dynamically add accessible routes
          resetRouter()
          // router.matcher = new VueRouter({ mode: 'history', routes: constantRoutes }).matcher;

          //   router.options.routes.push(...accessRoutes)
          router.addRoutes(accessRoutes)
          //   console.log(router)
          //   resolve(accessRoutes)
          resolve(data)
        })

      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // getInfo(state.token).then(response => {
      //   const { data } = response

      //   if (!data) {
      //     reject('Verification failed, please Login again.')
      //   }

      //   const { roles, name, avatar, introduction } = data

      //   // roles must be a non-empty array
      //   if (!roles || roles.length <= 0) {
      //     reject('getInfo: roles must be a non-null array!')
      //   }

      //   commit('SET_ROLES', roles)
      //   commit('SET_NAME', name)
      //   commit('SET_AVATAR', avatar)
      //   commit('SET_INTRODUCTION', introduction)
      //   resolve(data)
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // system userLogout
  userLogout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout({id: state.id}).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('set_Login', false)
        // removeToken()
        resetRouter()
        sessionStorage.clear()
        // this.$store.replaceState()
        // reset visited views and cached views
        // dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
